﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Globalization;

using CE.Mail;
using CE.Image;
using CE.Global;
using CE.Database;
using CE.User;
using CE.PostCode;
using CE.CarInsurance;
using CE.Provider;
using CE.Security;
using CE.InputOut;
using CE.StreetDirectory;
using CE.Payment;
using CXDecryption;

public partial class payment_default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Params["ref"] != null)
            {
                string CECarId = CE.Global.General.GetCarId(Request.Params["ref"].ToString());
                string OrderNumber = GetOrderNumber(Convert.ToInt64(CECarId));
                if (UpdateOrderRefNo(Convert.ToInt64(CECarId), OrderNumber) > 0)
                {
                    DataSet _dsApplication = new DataSet();
                    _dsApplication = GetCarDetails(Convert.ToInt64(CECarId));
                    if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
                    {
                        if (_dsApplication.Tables[2].Rows[0]["CancelStatus"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["CancelStatus"].ToString() != string.Empty
                             && _dsApplication.Tables[2].Rows[0]["CancelStatus"].ToString() == "1")
                        {
                            string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                            Session["UMMSG"] = "PAYMS,107";
                            CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody107, "107");
                            Response.Redirect(_redirectUrl);
                            return;
                        }
                        if (CheckOnlinePayment(_dsApplication))
                        {
                            if (CheckNonGGPayment(Convert.ToInt64(CECarId)))
                            {
                                float _fAmount = 0.0f;
                                if (_dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                                {
                                    _fAmount = Convert.ToSingle(_dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString());
                                    string _strAmount, eAmount, _strOrderRefNo, eOrderRefNo;
                                    _strAmount = ""; eAmount = ""; _strOrderRefNo = ""; eOrderRefNo = "";
                                    string key = "cxDAtravel";
                                    CXDecryption.Decryption cxd = new CXDecryption.Decryption();
                                    _strAmount = _fAmount.ToString();
                                    _strOrderRefNo = OrderNumber;
                                    if (_strAmount.ToString() != "" && _strAmount.ToString() != null)
                                    {
                                        byte[] Amount = cxd.Encrypt(_strAmount, key);
                                        eAmount = Convert.ToBase64String(Amount);
                                    }
                                    if (_strOrderRefNo.ToString() != "" && _strOrderRefNo.ToString() != null)
                                    {
                                        byte[] OrderRefNo = cxd.Encrypt(_strOrderRefNo, key);
                                        eOrderRefNo = Convert.ToBase64String(OrderRefNo);
                                    }
                                    string URL = ConfigurationManager.AppSettings["TH.BKKPaymentPage"].ToString();
                                    URL += "?pa=" + eAmount + "&orno=" + eOrderRefNo;

                                    Response.Redirect(URL);
                                }
                                else
                                {
                                    string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                                    Session["UMMSG"] = "PAYMS,101";
                                    CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody101, "101");
                                    Response.Redirect(_redirectUrl);
                                }
                            }
                            else
                            {
                                string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                                Session["UMMSG"] = "PAYMS,102";
                                CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody102, "102");
                                Response.Redirect(_redirectUrl);
                            }
                        }
                        else
                        {
                            string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                            Session["UMMSG"] = "PAYMS,103";
                            CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody103, "103");
                            Response.Redirect(_redirectUrl);
                        }
                    }
                    else
                    {
                        string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                        Session["UMMSG"] = "PAYMS,104";
                        CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody104, "104");
                        Response.Redirect(_redirectUrl);
                    }
                }
                else
                {
                    string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                    Session["UMMSG"] = "PAYMS,105";
                    CreatePaymentLog(Request.Params["ref"].ToString() + " - " + Resources.ErrorMessage.PayMsgBody105, "105");
                    Response.Redirect(_redirectUrl);
                }
            }
            else
            {
                string _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "PAYMS,106";
                CreatePaymentLog("[QuoteRefNo not Found] - " +  Resources.ErrorMessage.PayMsgBody106, "106");
                Response.Redirect(_redirectUrl);
            }
        }
    }

    public string GetOrderNumber(Int64 CarId)
    {
        string _result = "";
        string _onoffline = "2";
        string _firstno = DateTime.Now.ToString("yy") + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00") +
                          DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00");
        _result = _firstno + _onoffline + CarId.ToString("000000000");
        return _result;
    }

    public DataSet GetCarDetails(Int64 CarId)
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCXCRMNONGGPackageCarDetailsSelectedItemByCarId]";

        SortedList _spara = new SortedList();
        _spara.Add("@CarId", CarId);

        DataSet _ds = _db.GetDataSet(_spName, _spara);

        return _ds;
    }

    public bool CheckOnlinePayment(DataSet DS)
    {
        bool _result = true;
        if (DS != null && DS.Tables.Count > 4 && DS.Tables[4].Rows.Count > 0)
        {
            if (DS.Tables[2].Rows[0]["PaymentStatus"] != DBNull.Value && DS.Tables[2].Rows[0]["PaymentStatus"].ToString() != string.Empty &&
                DS.Tables[2].Rows[0]["PaymentStatus"].ToString().ToUpper() == "TRUE" && DS.Tables[2].Rows[0]["PaymentStatus"].ToString() == "1")
            {
                _result = false;
            }
        }
        return _result;
    }

    public bool CheckNonGGPayment(Int64 CECarId)
    {
        bool _result = true;
        MyDatabase _db = new MyDatabase();
        //string _spName = "[sprocCXCRMPaymentsDetailsSelectItemList]";

        //SortedList _spara = new SortedList();
        //_spara.Add("@CECarId", CECarId);
        //DataSet _ds = _db.GetDataSet(_spName, _spara);
        //if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
        //{
        //    _result = false;
        //}
        string strSql = "SELECT * FROM tblPayments WHERE CECarId  = " + CECarId.ToString() + " AND TransactionType = 1 AND ApproveType = 1 AND [Status] = 1";
        DataTable _Paymentresult = _db.GetDataTable(strSql);
        if (_Paymentresult != null && _Paymentresult.Rows.Count > 0)
        {
            _result = false;
        }
        return _result;
    }

    public Int64 UpdateOrderRefNo(Int64 CECarId, string OrderRefNo)
    {
        MyDatabase _db = new MyDatabase();
        Int64 _result = -1;
        string _spName = "[sprocCXNonGGOrderRefNoUpdatedSelectItem]";

        SortedList _sPara = new SortedList();
        #region Parameter
        _sPara.Add("@CECarId", CECarId);
        _sPara.Add("@OrderRefNo", OrderRefNo);
        #endregion

        _result = _db.ExecuteSP(_spName, _sPara);
        return _result;
    }

    public void CreatePaymentLog(string strError, string strErrorId)
    {
        String[] _fileContent = new String[3];
        _fileContent[0] = "Date Time : " + DateTime.Now.ToString();
        _fileContent[1] = "Message :" + strError;
        _fileContent[2] = "ErrorId :" + strErrorId;

        WriteExceptionLog("Payment_", _fileContent);
    }

    private void WriteExceptionLog(string strPrefixFileName, string[] strException)
    {
        try
        {
            MyIO _newFile = new MyIO();
            string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
            if (_newFile.CheckDirectory(_filePath))
            {
                string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                if (!_newFile.CheckDirectory(_filePath + _curMonth))
                {
                    if (_newFile.CreateDirectory(_filePath, _curMonth))
                    {
                        _filePath += _curMonth + "\\";
                    }
                }
                else
                {
                    _filePath += _curMonth + "\\";
                }

                string _fileName = strPrefixFileName + DateTime.Now.ToString("dd_MMM_yyyy_hh_mm_ss_tt", new System.Globalization.CultureInfo("en-US")) + ".txt";

                _newFile.WriteNewFile(_filePath, _fileName, strException);
                _newFile = null;
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

}
